//
//  FreshFoodShopBagView.swift
//  SmartHousekeeper
//
//  Created by 刘森 on 2020/2/21.
//  Copyright © 2020 LS. All rights reserved.
//

import UIKit

// MARK: -  购物袋
final class FreshFoodShopBagView: UIView {
    
    let cellRowHeight: CGFloat = 66
    static let sharedInstance = FreshFoodShopBagView()
    
    lazy var bottomView = FreshFoodBottomView()
    
    lazy var cancelButton = UIButton(backgroundColor: UIColor(hexString: "0x000000", alpha: 0.0001))
    lazy var bodyView = UIView(backgroundColor: UIColor.white)
    lazy var titleLabel: UILabel = {
        let value = UILabel(textColor: KColorRGBA(110, 110, 110), textFont: KFont(Adapter(14)))
        value.text = "新增商品将加入此购物车"
        return value
    }()
    lazy var titleLabelPlusLine = UIImageView(image: ImageName("fkLine"))
    lazy var clearButton: UIButton = {
        let value = UIButton(normalImage: ImageName("shopBag"))
        value.setTitle(" 清空购物袋", for: .normal)
        value.setTitleColor(KColorRGBA(110, 110, 110), for: .normal)
        value.titleLabel?.font = KFont(Adapter(14))
        return value
    }()
    public var tableViewCellTouch:((IndexPath) -> ())?
    lazy var tableView: UITableView = {
        let value = UITableView()
        value.delegate = self
        value.dataSource = self
        value.tableFooterView = UIView()
        value.showsVerticalScrollIndicator = false
        value.register(FreshFoodShopBagCell.self, forCellReuseIdentifier: "FreshFoodShopBagCell")
        value.rowHeight = cellRowHeight
        value.backgroundColor = UIColor.white
        return value
    }()
    var cellModels: [FreshFoodBaseCellModel]? {
        didSet {
            self.tableView.reloadData()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.isHidden = true
        self.backgroundColor = UIColor(hexString: "0x000000", alpha: 0.3)
        self.addSubviews([bottomView,cancelButton, bodyView])
        bodyView.addSubviews([titleLabel, titleLabelPlusLine, clearButton, tableView])
        
        initWithSubscribeSignal()
    }
    
    override func layoutSubviews() {
        
        bottomView.snp.makeConstraints { (make) in
            make.left.width.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(KSafeAreaBottom())
            make.height.equalTo(Adapter(88) + KSafeAreaBottom())
        }
        cancelButton.snp.makeConstraints { (make) in
            make.left.top.width.right.equalToSuperview()
            make.height.equalToSuperview().multipliedBy(0.4)
        }
        bodyView.snp.makeConstraints { (make) in
            make.left.width.right.equalToSuperview()
            make.top.equalTo(cancelButton.snp.bottom)
            make.bottom.equalTo(bottomView.snp.top)
        }
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(Adapter(22))
            make.top.equalToSuperview().offset(Adapter(cellRowHeight)/2 - 7)
        }
        titleLabelPlusLine.snp.makeConstraints { (make) in
            make.left.width.right.equalToSuperview()
            make.height.equalTo(1)
            make.centerY.equalTo(bodyView.snp.top).offset(cellRowHeight)
        }
        clearButton.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-Adapter(22))
            make.height.equalTo(Adapter(26))
            make.centerY.equalTo(titleLabel)
        }
        tableView.snp.makeConstraints { (make) in
            make.left.bottom.width.right.equalToSuperview()
            make.top.equalTo(titleLabelPlusLine.snp.bottom)
        }
        
        
    }
    
    override func draw(_ rect: CGRect) {
        let maskPath: UIBezierPath = UIBezierPath(roundedRect: bodyView.bounds, byRoundingCorners: UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue), cornerRadii: CGSize(width: 20, height: 20))
        let maskLayer: CAShapeLayer = CAShapeLayer()
        maskLayer.frame = bodyView.bounds
        maskLayer.path = maskPath.cgPath
        bodyView.layer.mask = maskLayer
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    class func show(models: [FreshFoodBaseCellModel]) {
        let shopBagView = FreshFoodShopBagView.sharedInstance
        if let window = KGetkeywindows(), shopBagView.isHidden {
            shopBagView.isHidden = false
            window.addSubview(shopBagView)
            shopBagView.snp.makeConstraints { (make) in
                make.edges.equalToSuperview()
            }
            shopBagView.cellModels = models

        }
    }
    func hidden(){
        let shopBagView = FreshFoodShopBagView.sharedInstance
        shopBagView.isHidden = true
        shopBagView.removeFromSuperview()
    }
}


extension FreshFoodShopBagView: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cellModels?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: FreshFoodShopBagCell = FreshFoodShopBagCell.baseCell(tableView, cellID: "FreshFoodShopBagCell") as! FreshFoodShopBagCell
        if let model = cellModels?[indexPath.row, true] {
            if let tempModel = model as? FreshFoodSecondLevelCellModel {
                cell.foodModel = tempModel
            }
            if let tempModel1 = model as? FreshFoodShopPostageModel {
                cell.postageModel = tempModel1
            }
        }
        return cell
    }
    
    
}
// MARK: - 购物袋点击事件
extension FreshFoodShopBagView {
    func initWithSubscribeSignal() {
        self.cancelButton.sce.add(.touchUpInside) { (button) in
            FreshFoodShopBagView.sharedInstance.hidden()
        }
        self.clearButton.sce.add(.touchUpInside) { [weak self] (button) in
            self?.cellModels?.removeAll()
            DispatchAfter(after: 0.3, handler: FreshFoodShopBagView.sharedInstance.hidden)
        }
    }
}




// MARK: - 购物袋单元格
enum FreshFoodShopBagCellType {
    case food
    case postage
}

class FreshFoodShopBagCell: UITableViewCell {
    
    
    lazy private var foodNameLabel: UILabel = {
        let value = UILabel(textColor: KColorRGBA(110, 110, 110), textFont: KFont(Adapter(15)))
        return value
    }()
    lazy private var foodPriceLabel: UILabel = {
        let value = UILabel(textColor: KColorRGBA(58, 130, 232), textFont: KFont(Adapter(16)))
        return value
    }()
    var addAndSubView: FreshFoodSecondLevelAddAndSubView?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.contentView.addSubviews([foodNameLabel, foodPriceLabel])
        self.selectionStyle = .none
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        foodNameLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(Adapter(22))
            make.centerY.equalToSuperview()
            make.right.lessThanOrEqualTo(self.snp.centerX)
        }
        foodPriceLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            if addAndSubView != nil {
                make.right.lessThanOrEqualTo(addAndSubView!.snp.left).offset(-Adapter(30))
                make.left.equalTo(self.snp.centerX)
                make.left.greaterThanOrEqualTo(foodNameLabel.snp.right).offset(Adapter(30))
            } else {
                make.left.equalTo(self.snp.centerX)
            }
        }
        addAndSubView?.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-Adapter(22))
            make.height.equalTo(Adapter(18))
        }
    }
    
    var foodModel: FreshFoodSecondLevelCellModel? {
        didSet {
            if addAndSubView == nil {
                addAndSubView = FreshFoodSecondLevelAddAndSubView()
                addAndSubView?.type = .limitOne
                self.contentView.addSubview(addAndSubView!)
            }
            self.foodNameLabel.text = self.foodModel?.foodName
            self.foodPriceLabel.text = "￥" + (self.foodModel?.foodPrice ?? "")
        }
    }
    
    var postageModel: FreshFoodShopPostageModel? {
        didSet {
            self.foodNameLabel.text = self.postageModel?.postageName
            self.foodPriceLabel.text = "￥" + (self.postageModel?.price ?? "")
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
